<template>
  <div>
    <div>
      <template v-if="invoiceMethod === 0">
        <div class="pad-t-3"></div>
        <div class="card-bar">
          <h2 class="flex v-align-c pad-t-8 pad-b-8">
            <div class="line mar-l-13 mar-r-7"></div>
            <div>发票详情和收件人信息</div>
          </h2>
          <div class="pad-t-23 pad-b-20 flex v-align-t">
            <div class="card-bar-con none">
              <h3 class="flex v-align-c">
                <div class="font-w">收件人信息</div>
                <el-button type="text" class="mar-l-17" @click="handleOpenSetInvoiceInfo(1)">修改</el-button>
              </h3>
              <div class="mar-l--14">
                <div class="flex v-align-c">
                  <div class="text-align-r label-l">收件人：</div>
                  <div>{{invoiceBaseInfoForm.recipient}}</div>
                </div>
                <div class="flex v-align-c">
                  <div class="text-align-r label-l">电话：</div>
                  <div>{{invoiceBaseInfoForm.receiptPhone}}</div>
                </div>
                <div class="flex v-align-t">
                  <div class="text-align-r label-l">地址：</div>
                  <div>{{invoiceBaseInfoForm.receiptAddress}}</div>
                </div>
              </div>
            </div>
            <div class="card-bar-con last">
              <h3 class="flex v-align-c">
                <div class="font-w">发票详情</div>
                <el-button type="text" class="mar-l-17" @click="handleOpenSetInvoiceInfo(2)">修改</el-button>
              </h3>
              <div class="flex v-align-t">
                <div v-if="invoiceBaseInfoForm.invoiceRiseType !== 1" class="card-bar-list last">
                  <div class="flex v-align-c">
                    <div class="text-align-r label-l">抬头类型：</div>
                    <div>{{invoiceRiseType[invoiceBaseInfoForm.invoiceRiseType]}}</div>
                  </div>
                  <div class="flex v-align-c">
                    <div class="text-align-r label-l">发票抬头：</div>
                    <div>{{invoiceBaseInfoForm.invoiceRise}}</div>
                  </div>
                  <div class="flex v-align-t">
                    <div class="text-align-r label-l">备注：</div>
                    <div>{{invoiceBaseInfoForm.remark}}</div>
                  </div>
                </div>
                <template v-else>
                  <div class="card-bar-list last">
                    <div class="flex v-align-c">
                      <div class="text-align-r label-l">抬头类型：</div>
                      <div>{{invoiceRiseType[invoiceBaseInfoForm.invoiceRiseType]}}</div>
                    </div>
                    <div class="flex v-align-c">
                      <div class="text-align-r label-l">发票类型：</div>
                      <div>{{invoiceBaseInfoForm ? invoiceType[invoiceBaseInfoForm.invoiceType] : ''}}</div>
                    </div>
                    <div class="flex v-align-c">
                      <div class="text-align-r label-l">发票抬头：</div>
                      <div>{{invoiceBaseInfoForm.invoiceRise}}</div>
                    </div>
                  </div>
                  <div class="card-bar-list last">
                    <div class="flex v-align-c">
                      <div class="text-align-r label-l">单位税号：</div>
                      <div>{{invoiceBaseInfoForm.distinguishNum}}</div>
                    </div>
                    <div class="flex v-align-c">
                      <div class="text-align-r label-l">单位电话：</div>
                      <div>{{invoiceBaseInfoForm.taxPhone}}</div>
                    </div>
                    <div class="flex v-align-t">
                      <div class="text-align-r label-l">单位地址：</div>
                      <div>{{invoiceBaseInfoForm.registerAddress}}</div>
                    </div>
                  </div>
                  <div class="card-bar-list last">
                    <div class="flex v-align-c">
                      <div class="text-align-r label-l">开户银行：</div>
                      <div>{{invoiceBaseInfoForm.accountBankInfo}}</div>
                    </div>
                    <div class="flex v-align-c">
                      <div class="text-align-r label-l">开户账号：</div>
                      <div>{{invoiceBaseInfoForm.bankCardNo}}</div>
                    </div>
                    <div class="flex v-align-t">
                      <div class="text-align-r label-l">备注：</div>
                      <div>{{invoiceBaseInfoForm.remark}}</div>
                    </div>
                  </div>
                </template>
              </div>
            </div>
          </div>
        </div>
      </template>
      <el-card class="box-card invoice-card" :style="invoiceMethod === 0 ? 'margin-top: 20px;':''">
        <div slot="header" class="clearfix font-16">
          <span>当前可开票总金额：<span
              class="color-money">￥{{canTotalInvoicePrice}}</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;当前开票明细：{{total}}条</span>
        </div>
        <div>
          <div class="mar-t--10 mar-b-10">
            <el-button type="text" icon="el-icon-plus" @click="handleAdd"
              :disabled="currentOpeartIndex >=0 || listLoading === true? true:false">添加开票明细</el-button>
            <el-button type="text" icon="el-icon-refresh" @click="handleRefreshInoviceDetail">刷新开票明细
            </el-button>
          </div>
          <!-- 内容列表 -->
          <div class="table-container" style="margin-bottom: 70px;">
            <el-table ref="multipleTable" :data="invoiceList" v-loading="listLoading"
              :element-loading-text="elementLoadingText" style="width: 100%" header-cell-class-name="default-header"
              row-class-name="default-row">
              <el-table-column label="开票订单" align="left" min-width="130">
                <template slot-scope="scope">
                  <div class="flex v-align-c">
                    <div v-if="scope.row.isEdit === 1" class="pad-r-13">
                      <el-button type="text" @click="handleOpenSelectOrder(scope.row)">选择订单</el-button>
                    </div>
                    <div>
                      <div v-for="(item,index) in scope.row.projectOrderDTOList" :key="item.orderId" class="text item">
                        <div class="flex v-align-c order-line-list">
                          <span class="line-prise-name">订单{{index + 1}}：</span>
                          <img class="width-16 height-16" :src="constant.platformIconObj[item.externalPlatformType]" />
                          <span
                            class="line-prise-or">￥{{invoiceMethod === 0 ? item.distributionAmount : item.orderPrice}}</span>
                          <el-button type="text" class="mar-l--5 mar-r--25" @click="handleOpenOrderDetail(item)">订单详情
                          </el-button>
                          <el-button type="text" size="mini" icon="el-icon-delete" v-if="scope.row.isEdit === 1"
                            @click="handleDeleteOrder(scope.row,index)">移除</el-button>
                        </div>
                      </div>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="开票金额" align="left" prop="amount">
                <template slot-scope="scope">
                  ￥{{scope.row.amount}}
                </template>
              </el-table-column>
              <el-table-column label="开票内容" align="left">
                <template slot-scope="scope">
                  <template v-if="scope.row.isEdit === 1">
                    <el-select class="select-class table-input" v-model="scope.row.invoiceContentId"
                      @change="handleChangeInvoiceContent($event,scope.$index)">
                      <el-option label="请选择开票内容" value="">
                      </el-option>
                      <el-option v-for="item in invoiceContentList" :key="item.invoiceContentId"
                        :label="item.invoiceContent" :value="item.invoiceContentId">
                      </el-option>
                    </el-select>
                  </template>
                  <template v-else>
                    {{scope.row.invoiceContent}}
                  </template>
                </template>
              </el-table-column>

              <el-table-column label="发票详情" align="left" v-if="invoiceMethod === 1">
                <template slot-scope="scope">
                  <template v-if="scope.row.isEdit === 1">
                    <el-button type="text" icon="el-icon-plus" @click="handleOpenSetInvoiceInfo(2,scope.$index)">设置
                    </el-button>
                  </template>
                  <template>
                    <div v-if="scope.row.invoiceRiseType">抬头类型：{{invoiceRiseType[scope.row.invoiceRiseType]}}</div>
                    <div v-if="scope.row.invoiceRiseType === 1 && scope.row.invoiceType">
                      发票类型：{{invoiceType[scope.row.invoiceType]}}</div>
                    <div v-if="scope.row.invoiceRise">发票抬头：{{scope.row.invoiceRise}}</div>
                    <div v-if="scope.row.invoiceRiseType === 1">
                      <div v-if="scope.row.distinguishNum">单位税号：{{scope.row.distinguishNum}}</div>
                      <div v-if="scope.row.registerAddress">单位地址：{{scope.row.registerAddress}}</div>
                      <div v-if="scope.row.taxPhone">单位电话：{{scope.row.taxPhone}}</div>
                      <div v-if="scope.row.accountBankInfo">开户银行：{{scope.row.accountBankInfo}}</div>
                      <div v-if="scope.row.bankCardNo">开户账号：{{scope.row.bankCardNo}}</div>
                    </div>
                    <div v-if="scope.row.remark">备注：{{scope.row.remark}}</div>

                  </template>
                </template>
              </el-table-column>
              <el-table-column label="收件人信息" align="left" v-if="invoiceMethod === 1">
                <template slot-scope="scope">
                  <template v-if="scope.row.isEdit === 1">
                    <el-button type="text" icon="el-icon-plus" @click="handleOpenSetInvoiceInfo(1,scope.$index)">设置
                    </el-button>
                  </template>
                  <template>
                    <div v-if="scope.row.recipient">收件人：{{scope.row.recipient}}</div>
                    <div v-if="scope.row.receiptPhone">电话：{{scope.row.receiptPhone}}</div>
                    <div v-if="scope.row.receiptAddress">地址：{{scope.row.receiptAddress}}</div>
                  </template>
                </template>
              </el-table-column>
              <el-table-column width="150px" label="操作" align="right" fixed="right">
                <template slot-scope="scope">
                  <div v-if="scope.row.isEdit === 1">
                    <el-button type="primary" size="mini" @click="handleSave(scope.row)">保存
                    </el-button>
                    <el-button size="mini" @click="handleCancelEdit(scope.row)">
                      取消</el-button>
                  </div>
                  <template v-else>
                    <el-button type="text" size="mini" @click="handleEdit(scope.row,scope.$index)">编辑
                    </el-button>
                    <el-button type="text" size="mini" @click="handleDelete(scope.row,scope.$index)">
                      删除</el-button>
                  </template>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-card>
    </div>
    <div class="bottom-bar invoice-bottom">
      <el-button type="primary" @click="handleSaveInvoice" :loading="isSubmitInvoiceLoading"
        :disabled="currentOpeartIndex >=0? true:false">{{submitInvoiceButtonText}}
      </el-button>
      <span class="font-18" style="color: #333333;margin-left: 15px;">
        开票金额：<span class="color-money">￥{{totalPrice}}</span></span>
      <div class="flex-item"></div>
    </div>
    <el-dialog title="设置发票" :visible.sync="invoiceInfoVisibleDialog" width="35%" :close-on-press-escape="false"
      append-to-body>
      <div class="scroll-layer-box invoice-scr-basefm mar-b-10">
        <el-form class="mar-15" :model="editInvoiceBaseInfoForm" :rules="invoiceInfoRules" ref="invoiceBaseInfoFormRef"
          label-width="140px">
          <h4 class="title-layer-bar flex v-align-c">
            <div class="line"></div>
            <div>发票详情</div>
          </h4>
          <div class="pad-t-26"></div>
          <el-form-item label="抬头类型：" prop="invoiceRiseType">
            <el-radio-group v-model="editInvoiceBaseInfoForm.invoiceRiseType">
              <el-radio :label="0">个人/非企业</el-radio>
              <el-radio :label="1">企业单位</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="发票类型：" prop="invoiceType" v-if="editInvoiceBaseInfoForm.invoiceRiseType === 1">
            <el-radio-group v-model="editInvoiceBaseInfoForm.invoiceType">
              <el-radio :label="0">增值税普通发票</el-radio>
              <el-radio :label="1">增值税专用发票</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="发票抬头：" prop="invoiceRise">
            <el-input v-model="editInvoiceBaseInfoForm.invoiceRise" placeholder="请输入发票抬头" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="单位税号：" prop="distinguishNum" v-if="editInvoiceBaseInfoForm.invoiceRiseType === 1">
            <el-input v-model="editInvoiceBaseInfoForm.distinguishNum" placeholder="请输入单位税号" autocomplete="off">
            </el-input>
          </el-form-item>
          <el-form-item label="单位地址：" prop="registerAddress" v-if="editInvoiceBaseInfoForm.invoiceRiseType === 1">
            <el-input v-model="editInvoiceBaseInfoForm.registerAddress" placeholder="选填" type="textarea" :rows="2"
              autocomplete="off">
            </el-input>
          </el-form-item>
          <el-form-item label="单位电话：" prop="taxPhone" v-if="editInvoiceBaseInfoForm.invoiceRiseType === 1">
            <el-input v-model="editInvoiceBaseInfoForm.taxPhone" placeholder="选填" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="开户银行：" prop="accountBankInfo" x v-if="editInvoiceBaseInfoForm.invoiceRiseType === 1">
            <el-input v-model="editInvoiceBaseInfoForm.accountBankInfo" placeholder="选填" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="银行账户：" prop="bankCardNo" v-if="editInvoiceBaseInfoForm.invoiceRiseType === 1">
            <el-input v-model="editInvoiceBaseInfoForm.bankCardNo" placeholder="选填" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="备注信息：" prop="remark">
            <el-input v-model="editInvoiceBaseInfoForm.remark" placeholder="选填" autocomplete="off"></el-input>
          </el-form-item>
          <h4 class="title-layer-bar flex v-align-c">
            <div class="line"></div>
            <div>收件人信息</div>
          </h4>
          <div class="pad-t-26"></div>
          <el-form-item label="收件人：" prop="recipient">
            <el-input v-model="editInvoiceBaseInfoForm.recipient" placeholder="请输入收件人" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="电话：" prop="receiptPhone">
            <el-input v-model="editInvoiceBaseInfoForm.receiptPhone" placeholder="请输入收件人电话" maxlength="11"
              autocomplete="off">
            </el-input>
          </el-form-item>
          <el-form-item label="地址：" prop="receiptAddress">
            <el-input v-model="editInvoiceBaseInfoForm.receiptAddress" placeholder="请输入收件人地址" autocomplete="off"
              type="textarea" :rows="2">
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancelSetInvoiceInfo">取 消</el-button>
        <el-button type="primary" @click="handleSaveInvoiceInfo">确 定</el-button>
      </div>
    </el-dialog>
    <OrderListSelect ref="orderListSelectRef" :onSureCall="onSureSelectOrderCall">
    </OrderListSelect>
  </div>
</template>
<script>
  import {
    saveBaseAndReceiptInfo,
    deleteInvoice,
    save,
    getInvoiceList,
    doBatchUpdateStatus,
    getCanInvoiceTotalAmount
  } from '@/api/invoice/invoice'
  import {
    getInvoiceContentList
  } from '@/api/invoice/invoiceContent'
  import {
    getDetailByMemberIdAndType,
    saveInvoiceMemberBaseInfo
  } from '@/api/invoice/invoiceMemberBaseInfo'
  import OrderListSelect from '../order-select/index.vue'

  export default {
    props: {
      // 开票方式 0:申请开票  1:平台代开。默认：0
      invoiceMethod: {
        type: Number,
        default: 0
      }
    },
    components: {
      OrderListSelect
    },
    data() {
      return {
        invoiceType: {
          0: '增值税普通发票',
          1: '增值税专用发票'
        },
        invoiceRiseType: {
          0: '个人',
          1: '企业'
        },
        listLoading: false,
        total: 0,
        queryParams: {
          enterpriseId: this.getEnterpriseId(),
          applyId: this.getMemberId(),
          status: 0
        },
        totalPrice: 0.00,
        // 能开票总金额
        canTotalInvoicePrice: 0.00,
        invoiceList: [],
        invoiceContentList: [],
        submitInvoiceButtonText: '申请开票',
        isSubmitInvoiceLoading: false,
        invoiceBaseInfoForm: {
          invoiceRiseType: '',
          invoiceType: '',
          recipient: '',
          receiptPhone: '',
          receiptAddress: '',
          invoiceRise: '',
          distinguishNum: '',
          registerAddress: '',
          taxPhone: '',
          accountBankInfo: '',
          bankCardNo: '',
          remark: ''
        },
        // 当前操作的对象赋值，为了后续要返回原来的值
        currentOpeartItemCopy: {},
        // 当前操作的行数
        currentOpeartIndex: -1,
        // 角色类型：0-经销商
        memberType: 0,
        invoiceInfoVisibleDialog: false,
        invoiceInfoRules: {
          recipient: [{
            required: true,
            message: '请填写收件人',
            trigger: 'blur'
          }],
          receiptPhone: [{
            required: true,
            message: '请填写收件人电话',
            pattern: /^(4|8)[0-9]{2,3}-[0-9]{3,4}-[0-9]{3,4}$|1(3|4|5|6|7|8|9)([0-9]{9})$|0[0-9]{2,3}-[0-9]{7,8}$/,
            trigger: 'blur'
          }],
          receiptAddress: [{
            required: true,
            message: '请填写收件人地址',
            trigger: 'blur'
          }],
          invoiceRiseType: [{
            required: true,
            message: '请选择抬头类型',
            trigger: 'change'
          }],
          invoiceType: [{
            required: true,
            message: '请选择发票类型',
            trigger: 'change'
          }],
          invoiceRise: [{
            required: true,
            message: '请填写发票抬头',
            trigger: 'blur'
          }],
          distinguishNum: [{
            required: true,
            message: '请填写单位税号',
            trigger: 'blur'
          }]
        },
        editInvoiceBaseInfoForm: {
          invoiceRiseType: '',
          invoiceType: '',
          recipient: '',
          receiptPhone: '',
          receiptAddress: '',
          invoiceRise: '',
          distinguishNum: '',
          registerAddress: '',
          taxPhone: '',
          accountBankInfo: '',
          bankCardNo: '',
          remark: ''
        },
        selectOrderVisibleDialog: false,
        elementLoadingText: '加载中'
      }
    },
    created() {
      this.getInvoiceContentList()
      if (this.invoiceMethod === 0) {
        this.getInvoiceMemberBaseInfo()
      }
      this.getInvoiceList()
    },
    methods: {
      // 申请开票
      handleSaveInvoice() {
        if (this.currentOpeartIndex >= 0) {
          this.$message({
            type: 'error',
            message: '有正在操作的数据，请先保存后再申请!'
          })
          return
        }
        if (!this.invoiceList || this.invoiceList.length <= 0) {
          this.$message({
            type: 'error',
            message: '请添加开票明细!'
          })
          return
        }
        var query = {
          enterpriseId: this.getEnterpriseId(),
          applyId: this.getMemberId(),
          status: 1,
          invoiceMethod: this.invoiceMethod
        }
        var invoiceIdList = []
        this.invoiceList.forEach((item) => {
          if (item.invoiceId) {
            invoiceIdList.push(item.invoiceId)
          }
        })
        query.invoiceIdList = invoiceIdList
        this.isSubmitInvoiceLoading = true
        this.submitInvoiceButtonText = '正在提交申请开票中...'
        doBatchUpdateStatus(query).then(response => {
          this.submitInvoiceButtonText = '申请开票'
          this.isSubmitInvoiceLoading = false
          if (response.isError) return
          this.$message({
            type: 'success',
            message: '申请开票成功'
          })
          // this.getInvoiceList()
          var params = {}
          this.$router.push({
            path: '/finace/invoice-sub-manage/index',
            query: params
          })
        })
      },
      // 初始化一条新的发票数据，默认添加在第一条
      initNewInvoiceData() {
        var options = {
          enterpriseId: this.getEnterpriseId(),
          applyType: this.memberType,
          applyId: this.getMemberId(),
          amount: 0.00,
          invoiceContentId: '',
          baseInfoId: '',
          status: 0,
          isEdit: 1,
          invoiceMethod: this.invoiceMethod
        }
        var invoiceBaseInfoForm
        if (this.invoiceMethod === 0) {
          invoiceBaseInfoForm = this.invoiceBaseInfoForm
        }
        this.$set(options, 'invoiceRiseType', invoiceBaseInfoForm && invoiceBaseInfoForm.invoiceRiseType || 0)
        this.$set(options, 'invoiceRise', invoiceBaseInfoForm && invoiceBaseInfoForm.invoiceRise || '')
        this.$set(options, 'invoiceType', invoiceBaseInfoForm && invoiceBaseInfoForm.invoiceType || 0)
        this.$set(options, 'distinguishNum', invoiceBaseInfoForm && invoiceBaseInfoForm.distinguishNum || '')
        this.$set(options, 'registerAddress', invoiceBaseInfoForm && invoiceBaseInfoForm.registerAddress || '')
        this.$set(options, 'taxPhone', invoiceBaseInfoForm && invoiceBaseInfoForm.taxPhone || '')
        this.$set(options, 'accountBankInfo', invoiceBaseInfoForm && invoiceBaseInfoForm.accountBankInfo || '')
        this.$set(options, 'bankCardNo', invoiceBaseInfoForm && invoiceBaseInfoForm.bankCardNo || '')
        this.$set(options, 'remark', invoiceBaseInfoForm && invoiceBaseInfoForm.remark || '')
        this.$set(options, 'recipient', invoiceBaseInfoForm && invoiceBaseInfoForm.recipient || '')
        this.$set(options, 'receiptPhone', invoiceBaseInfoForm && invoiceBaseInfoForm.receiptPhone || '')
        this.$set(options, 'receiptAddress', invoiceBaseInfoForm && invoiceBaseInfoForm.receiptAddress || '')
        this.invoiceList.unshift(options)
        this.currentOpeartIndex = 0
        this.statistics()
      },
      handleAdd(item) {
        // 说明有数据在操作，需要自动保存。保存成功了才能新增一条新的
        if (this.currentOpeartIndex >= 0) {
          this.handleSave(undefined, true)
        } else {
          this.initNewInvoiceData()
        }
      },
      handleSave(item, isNewAddSave) {
        var validData
        if (this.invoiceMethod === 0) {
          validData = this.invoiceBaseInfoForm
        } else {
          if (item) {
            validData = item
          } else {
            // 新增的保存
            validData = this.invoiceList[this.currentOpeartIndex]
          }
        }
        if (!item) {
          item = this.invoiceList[this.currentOpeartIndex]
        }
        if (this.valid(validData, isNewAddSave)) {
          var tips = ''
          if (isNewAddSave) {
            tips = '，才能保存，保存后才能新增开票明细！'
          }
          if (!item.invoiceContentId) {
            this.$message({
              type: 'error',
              message: '请选择开票内容' + tips + '!'
            })
            return false
          }
          if (!item.orderIdList || item.orderIdList.length === 0) {
            this.$message({
              type: 'error',
              message: '请选择订单' + tips + '!'
            })
            return false
          }
          if (isNewAddSave) {
            this.currentOpeartIndex = -1
            item.isEdit = 0
            this.initNewInvoiceData()
          } else {
            this.listLoading = true
            save(item).then(response => {
              if (response.isError) {
                this.listLoading = false
                return
              }
              this.$message({
                type: 'success',
                message: '保存成功'
              })
              this.currentOpeartIndex = -1
              this.getInvoiceList()
            })
          }
        }
      },
      valid(item, isNewAddSave) {
        var tips = ''
        if (isNewAddSave) {
          tips = '后，才能保存，保存后才能新增开票！'
        }
        if (item.invoiceRiseType === '' || item.invoiceRiseType === null || item.invoiceRiseType === undefined) {
          this.$message({
            type: 'error',
            message: '请完善发票详情(发票抬头类型)' + tips + '!'
          })
          return false
        }
        if (!item.invoiceRise) {
          this.$message({
            type: 'error',
            message: '请完善发票详情(发票抬头)' + tips + '!'
          })
          return false
        }
        // 发票抬头类型是：企业，要校验企业的信息
        if (item.invoiceRiseType === 1) {
          if (item.invoiceType === '' || item.invoiceType === null || item.invoiceType === undefined) {
            this.$message({
              type: 'error',
              message: '请完善发票详情(发票类型)' + tips + '!'
            })
            return false
          }
          if (!item.distinguishNum) {
            this.$message({
              type: 'error',
              message: '请完善发票详情(单位税号)' + tips + '!'
            })
            return false
          }
        }
        if (!item.recipient) {
          this.$message({
            type: 'error',
            message: '请完善收件人信息(收件人)' + tips + '!'
          })
          return false
        }
        if (!item.receiptPhone) {
          this.$message({
            type: 'error',
            message: '请完善收件人信息(收件人电话)' + tips + '!'
          })
          return false
        }
        if (!item.receiptAddress) {
          this.$message({
            type: 'error',
            message: '请完善收件人信息(收件人地址)' + tips + '!'
          })
          return false
        }
        return true
      },
      handleCancelEdit(item) {
        if (item.invoiceId) {
          this.currentOpeartItemCopy.isEdit = 0
          this.invoiceList.splice(this.currentOpeartIndex, 1, JSON.parse(JSON.stringify(this.currentOpeartItemCopy)))
        } else {
          this.invoiceList.splice(this.currentOpeartIndex, 1)
          this.statistics()
        }
        this.currentOpeartIndex = -1
      },
      handleEdit(item, opeartIndex) {
        // 说明有数据在操作，需要自动保存。保存成功了才能新增一条新的
        if (this.currentOpeartIndex >= 0) {
          this.$confirm('有正在编辑的数据，需要先保存才能再次编辑，确定要保存吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.handleSave(this.invoiceList[this.currentOpeartIndex], false)
          }).catch(() => {})
        } else {
          item.isEdit = 1
          this.currentOpeartItemCopy = JSON.parse(JSON.stringify(item))
          // this.currentOpeartItemCopy = Object.create(item)
          this.currentOpeartIndex = opeartIndex
          this.invoiceList.splice(opeartIndex, 1, item)
        }
      },
      handleDelete(item, index) {
        if (item.invoiceId) {
          this.$confirm('确定要删除发票吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.listLoading = true
            this.elementLoadingText = '正在删除数据中...'
            deleteInvoice(item.invoiceId).then(response => {
              this.listLoading = false
              if (response.isError) {
                return
              }
              this.$message({
                type: 'success',
                message: '删除成功'
              })
              this.invoiceList.splice(index, 1)
              this.statistics()
            })
          }).catch(() => {})
        } else {
          this.invoiceList.splice(item, 1)
          this.statistics()
        }
      },
      handleDeleteOrder(invoiceItem, orderIndex) {
        if (this.currentOpeartIndex >= 0) {
          this.$confirm('确定要移除订单吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            invoiceItem.projectOrderDTOList.splice(orderIndex, 1)
            invoiceItem.orderIdList.splice(orderIndex, 1)
            var totalPrice = 0
            var totalFreight = 0
            invoiceItem.projectOrderDTOList.forEach((item) => {
              if (this.invoiceMethod === 0) {
                totalPrice = parseFloat(totalPrice) + parseFloat(item.distributionAmount)
              } else {
                totalPrice = parseFloat(totalPrice) + parseFloat(item.orderPrice)
                totalFreight = parseFloat(totalFreight) + parseFloat(item.freight)
              }
            })
            invoiceItem.freight = totalFreight
            invoiceItem.amount = totalPrice.toFixed(2)
            this.statistics()
            this.$message({
              type: 'success',
              message: '移除成功'
            })
          }).catch(() => {})
        }
      },
      handleOpenSelectOrder(item) {
        var selectOrderIdList = []
        if (item.orderIdList && item.orderIdList.length > 0) {
          selectOrderIdList = item.orderIdList
        }
        var notInvoiceIds = []
        if (item.invoiceId) {
          notInvoiceIds.push(item.invoiceId)
        }
        this.$refs.orderListSelectRef.open(this.invoiceMethod, selectOrderIdList, notInvoiceIds)
      },
      handleChangeInvoiceContent(invoiceContentId, index) {
        const invoiceContentData = this.invoiceContentList.find((i) => {
          return i.invoiceContentId === invoiceContentId
        })
        var invoiceContent = invoiceContentData.invoiceContent
        this.$set(this.invoiceList[index], 'invoiceContentId', invoiceContentId)
        this.$set(this.invoiceList[index], 'invoiceContent', invoiceContent)
      },
      handleRefreshInoviceDetail() {
        if (this.currentOpeartIndex >= 0) {
          this.$confirm('还有未保存的数据，刷新就没有了，确认还要刷新吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.getInvoiceList()
          }).catch(() => {})
        } else {
          this.getInvoiceList()
        }
      },
      // 跳转到订单详情
      handleOpenOrderDetail(orderRow) {
        const routeData = this.$router.resolve({
          path: '/order/order/detail/index',
          query: {
            orderId: orderRow.orderId
          }
        })
        window.open(routeData.href, '_blank')
      },
      // 获取开票列表
      getInvoiceList() {
        this.queryParams.invoiceMethod = this.invoiceMethod
        this.queryParams.applyType = this.memberType
        this.listLoading = true
        this.currentOpeartIndex = -1
        this.elementLoadingText = '加载中'
        getInvoiceList(this.queryParams).then(response => {
          if (response.isError) return
          this.invoiceList = response.data
          if (this.invoiceList) {
            for (var i = 0; i < this.invoiceList.length; i++) {
              this.invoiceList[i].isEdit = 0
            }
          }
          this.statistics()
          this.listLoading = false
        })
      },
      getInvoiceContentList() {
        // enterpriseId: this.getEnterpriseId(),
        // supplierId: this.getSupplierId(),
        // memberId: this.getMemberId(),
        getInvoiceContentList({
          enterpriseId: this.getEnterpriseId()
        }).then(response => {
          this.invoiceContentList = response.data
        })
      },
      getInvoiceMemberBaseInfo() {
        getDetailByMemberIdAndType(this.getMemberId(), this.memberType).then(response => {
          if (response.isError) return
          if (response.data) {
            this.invoiceBaseInfoForm = response.data
          }
        })
      },
      // 设置发票信息，setInvoiceType：1- 收件人，2-发票信息
      // index 索引
      handleOpenSetInvoiceInfo(setInvoiceType, index) {
        this.currentOpeartIndex = index
        this.convertInvoiceInfo(true)
        this.invoiceInfoVisibleDialog = true
      },
      handleCancelSetInvoiceInfo() {
        this.invoiceInfoVisibleDialog = false
        this.$refs['invoiceBaseInfoFormRef'].resetFields()
      },
      handleSaveInvoiceInfo() {
        this.$refs['invoiceBaseInfoFormRef'].validate((valid) => {
          if (valid) {
            if (this.invoiceMethod === 1) {
              if (this.invoiceBaseInfoForm.invoiceId) {
                // 调用方法保存
                saveBaseAndReceiptInfo(this.editInvoiceBaseInfoForm).then(response => {
                  if (response.isError) return
                  this.invoiceInfoVisibleDialog = false
                  this.$message({
                    type: 'success',
                    message: '保存成功'
                  })
                })
              } else {
                this.invoiceInfoVisibleDialog = false
              }
              this.convertInvoiceInfo(false)
            } else {
              saveInvoiceMemberBaseInfo(this.editInvoiceBaseInfoForm).then(response => {
                if (response.isError) return
                this.invoiceInfoVisibleDialog = false
                this.$message({
                  type: 'success',
                  message: '保存成功'
                })
                this.getInvoiceMemberBaseInfo()
              })
            }
          }
        })
      },
      // 统计：金额，数量等
      statistics() {
        // 数量
        var total = 0
        // 开票金额
        var totalPrice = 0
        if (this.invoiceList && this.invoiceList.length > 0) {
          total = this.invoiceList.length
          this.invoiceList.forEach((item, index) => {
            var amount = 0
            if (item.amount) {
              amount = item.amount
            }
            totalPrice = parseFloat(totalPrice) + parseFloat(amount)
          })
        }
        this.total = total
        this.totalPrice = totalPrice.toFixed(2)
        this.getCanInvoiceTotalAmount()
      },
      // 获取总的能开票金额
      getCanInvoiceTotalAmount() {
        var orderTypes = [33]
        var query = {
          enterpriseId: this.getEnterpriseId(),
          applyId: this.getMemberId(),
          status: 1,
          invoiceMethod: this.invoiceMethod,
          orderTypes: orderTypes
        }
        getCanInvoiceTotalAmount(query).then(response => {
          if (response.isError) return
          var canTotalInvoicePrice = 0
          canTotalInvoicePrice = parseFloat(response.data) - parseFloat(this.totalPrice)
          if (canTotalInvoicePrice < 0) {
            canTotalInvoicePrice = 0
          }
          this.canTotalInvoicePrice = canTotalInvoicePrice.toFixed(2)
        })
      },
      // 发票信息转换，isEdit == true invoiceBaseInfoForm copy 给 editInvoiceBaseInfoForm ，否则 反之
      convertInvoiceInfo(isEdit) {
        var index = this.currentOpeartIndex
        if (isEdit) {
          var copyData
          if (this.invoiceMethod === 1) {
            copyData = this.invoiceList[index]
            this.editInvoiceBaseInfoForm.invoiceId = copyData.invoiceId
          } else {
            copyData = this.invoiceBaseInfoForm
            this.editInvoiceBaseInfoForm.baseInfoId = copyData.baseInfoId
          }
          this.editInvoiceBaseInfoForm.invoiceRiseType = copyData.invoiceRiseType || 0
          if (copyData.invoiceRiseType === 1) {
            this.editInvoiceBaseInfoForm.invoiceType = copyData.invoiceType || 0
            this.editInvoiceBaseInfoForm.distinguishNum = copyData.distinguishNum
            this.editInvoiceBaseInfoForm.registerAddress = copyData.registerAddress
            this.editInvoiceBaseInfoForm.taxPhone = copyData.taxPhone
            this.editInvoiceBaseInfoForm.accountBankInfo = copyData.accountBankInfo
            this.editInvoiceBaseInfoForm.bankCardNo = copyData.bankCardNo
          } else {
            this.editInvoiceBaseInfoForm.invoiceType = 0
            this.editInvoiceBaseInfoForm.distinguishNum = ''
            this.editInvoiceBaseInfoForm.registerAddress = ''
            this.editInvoiceBaseInfoForm.taxPhone = ''
            this.editInvoiceBaseInfoForm.accountBankInfo = ''
            this.editInvoiceBaseInfoForm.bankCardNo = ''
          }
          this.editInvoiceBaseInfoForm.recipient = copyData.recipient
          this.editInvoiceBaseInfoForm.receiptPhone = copyData.receiptPhone
          this.editInvoiceBaseInfoForm.receiptAddress = copyData.receiptAddress
          this.editInvoiceBaseInfoForm.invoiceRise = copyData.invoiceRise
          this.editInvoiceBaseInfoForm.remark = copyData.remark
          this.editInvoiceBaseInfoForm.enterpriseId = this.getEnterpriseId()
          this.editInvoiceBaseInfoForm.memberId = this.getMemberId()
          this.editInvoiceBaseInfoForm.memberType = this.memberType
        } else {
          if (this.invoiceMethod === 1) {
            this.invoiceList[index].invoiceRiseType = this.editInvoiceBaseInfoForm.invoiceRiseType
            if (this.editInvoiceBaseInfoForm.invoiceRiseType === 1) {
              this.invoiceList[index].invoiceType = this.editInvoiceBaseInfoForm.invoiceType
              this.invoiceList[index].distinguishNum = this.editInvoiceBaseInfoForm.distinguishNum
              this.invoiceList[index].registerAddress = this.editInvoiceBaseInfoForm.registerAddress
              this.invoiceList[index].taxPhone = this.editInvoiceBaseInfoForm.taxPhone
              this.invoiceList[index].accountBankInfo = this.editInvoiceBaseInfoForm.accountBankInfo
              this.invoiceList[index].bankCardNo = this.editInvoiceBaseInfoForm.bankCardNo
            } else {
              this.invoiceList[index].invoiceType = 0
              this.invoiceList[index].distinguishNum = ''
              this.invoiceList[index].registerAddress = ''
              this.invoiceList[index].taxPhone = ''
              this.invoiceList[index].accountBankInfo = ''
              this.invoiceList[index].bankCardNo = ''
            }
            this.invoiceList[index].recipient = this.editInvoiceBaseInfoForm.recipient
            this.invoiceList[index].receiptPhone = this.editInvoiceBaseInfoForm.receiptPhone
            this.invoiceList[index].receiptAddress = this.editInvoiceBaseInfoForm.receiptAddress
            this.invoiceList[index].invoiceRise = this.editInvoiceBaseInfoForm.invoiceRise
            this.invoiceList[index].remark = this.editInvoiceBaseInfoForm.remark
          } else {
            this.invoiceBaseInfoForm.invoiceRiseType = this.editInvoiceBaseInfoForm.invoiceRiseType
            if (this.editInvoiceBaseInfoForm.invoiceRiseType === 1) {
              this.invoiceBaseInfoForm.invoiceType = this.editInvoiceBaseInfoForm.invoiceType
              this.invoiceBaseInfoForm.distinguishNum = this.editInvoiceBaseInfoForm.distinguishNum
              this.invoiceBaseInfoForm.registerAddress = this.editInvoiceBaseInfoForm.registerAddress
              this.invoiceBaseInfoForm.taxPhone = this.editInvoiceBaseInfoForm.taxPhone
              this.invoiceBaseInfoForm.accountBankInfo = this.editInvoiceBaseInfoForm.accountBankInfo
              this.invoiceBaseInfoForm.bankCardNo = this.editInvoiceBaseInfoForm.bankCardNo
            } else {
              this.invoiceBaseInfoForm.invoiceType = 0
              this.invoiceBaseInfoForm.distinguishNum = ''
              this.invoiceBaseInfoForm.registerAddress = ''
              this.invoiceBaseInfoForm.taxPhone = ''
              this.invoiceBaseInfoForm.accountBankInfo = ''
              this.invoiceBaseInfoForm.bankCardNo = ''
            }
            this.invoiceBaseInfoForm.recipient = this.editInvoiceBaseInfoForm.recipient
            this.invoiceBaseInfoForm.receiptPhone = this.editInvoiceBaseInfoForm.receiptPhone
            this.invoiceBaseInfoForm.receiptAddress = this.editInvoiceBaseInfoForm.receiptAddress
            this.invoiceBaseInfoForm.invoiceRise = this.editInvoiceBaseInfoForm.invoiceRise
            this.invoiceBaseInfoForm.remark = this.editInvoiceBaseInfoForm.remark
          }
        }
      },
      // 确认选择订单的回调
      onSureSelectOrderCall(list) {
        if (list && list.length > 0) {
          var currentOrderList = this.invoiceList[this.currentOpeartIndex].projectOrderDTOList
          if (!currentOrderList) {
            currentOrderList = []
          }
          var orderIdList = this.invoiceList[this.currentOpeartIndex].orderIdList
          if (!orderIdList) {
            orderIdList = []
          }
          list.forEach((item) => {
            orderIdList.push(item.orderId)
            currentOrderList.push(item)
          })
          var freight = 0
          var totalPrice = 0
          currentOrderList.forEach((item) => {
            if (this.invoiceMethod === 0) {
              totalPrice = parseFloat(totalPrice) + parseFloat(item.distributionAmount || 0)
            } else {
              totalPrice = parseFloat(totalPrice) + parseFloat(item.orderPrice)
              freight = parseFloat(freight) + parseFloat(item.freight)
            }
          })
          this.$set(this.invoiceList[this.currentOpeartIndex], 'projectOrderDTOList', currentOrderList)
          this.$set(this.invoiceList[this.currentOpeartIndex], 'orderIdList', orderIdList)
          this.$set(this.invoiceList[this.currentOpeartIndex], 'amount', totalPrice.toFixed(2))
          this.$set(this.invoiceList[this.currentOpeartIndex], 'freight', freight.toFixed(2))
          this.statistics()
        }
      }
    }
  }
</script>

<style lang="less" scoped>
  .order-line-list {
    .line-prise-name {
      min-width: 51px;
      display: inline-block;
    }

    .line-prise-or {
      min-width: 70px;
    }

    .el-button {
      padding: 0px 20px;
    }
  }

  .invoice-card {
    &.el-card {
      border-radius: 0;
      box-shadow: 0 0 0;
      border: none;
    }
  }

  .color-money {
    color: #ffaa30;
  }

  // .box-card {
  //   /deep/ .el-card__header {
  //     line-height: 5px;
  //     background-color: #ccc;
  //   }
  // }
</style>
